package edu.lsnu.equipment_management_system.controller;

import edu.lsnu.equipment_management_system.mapper.select.nopaging.LoginCheckMapper;
import edu.lsnu.equipment_management_system.pojo.domain.JsonData;
import edu.lsnu.equipment_management_system.pojo.vo.out.session.UserVo;
import edu.lsnu.equipment_management_system.service.ChangePasswordService;
import edu.lsnu.equipment_management_system.util.MD5Util;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author mzy
 * @Description 这里写登陆相关的操作：
 *      1.普通用户登陆 表单提交
 *      2.管理员登陆  表单提交
 *      3.普通用户登出 session remove
 *      4.管理员登出 session remove
 *
 *
 *      5.获取此刻普通用户session
 *      6.获取此刻管理员用户的session
 *
 *      7.普通用户修改密码
 *      8.管理员修改密码
 * @date 2018/11/16
 *
 * 注意回忆：Model、ModelMap是用来装值
 * 便于后面渲染的，但是不是用来接收值的！
 * 以上两种直接参数注入就行。
 *
 * ModelAndView要手动创建
 */
@Controller
@Data
@PropertySource({"classpath:resource.properties"})
@ConfigurationProperties(prefix = "role")
public class LoginController {
    private String admin;
    @Autowired
    LoginCheckMapper loginCheckMapper;
    @Autowired
    ChangePasswordService changePasswordService;
    /**
     * @Description 1.普通用户登陆的表单提交地址
     * @author mzy
     * @time 2018-11-19
     * @see
     * @return   java.lang.String
     * @params  [UserNo, password, modelMap]
     */
    @PostMapping("/login/user")
    public String userLogin(@RequestParam("username") String UserNo,
                            String password, ModelMap modelMap, HttpServletRequest request) {
        // System.err.println(UserNo +", "+password);
        // 查询出user对象
        UserVo user = loginCheckMapper.getUser(UserNo);
        // 应刘老要求，禁止管理员前台登录功能。
        String roleNo = user.getRoleNo();
        if (admin.equals(roleNo)) {
            modelMap.addAttribute("msg", "系统管理员禁止登录前台！");
            return "forward:/login/user.html";
        }

        // 调用抽离的chekLogin方法判断
        String result = checkLogin(user, UserNo, password);
        if ("right".equals(result)) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            // 不用默认的转发，使用重定向的方式
            return "redirect:/page/user/index.html";
        }

        modelMap.addAttribute("msg", result);

        return "forward:/login/user.html";
    }

    /**
     * @Description 2.系统管理员登陆的表单提交地址
     * @author mzy
     * @time 2018-11-19
     * @see
     * @return   java.lang.String
     * @params  [UserNo, password, modelMap]
     */
    @PostMapping("/login/admin")
    public String adminLogin(@RequestParam("username") String UserNo,
                        String password, ModelMap modelMap, HttpServletRequest request) {
        // System.err.println(UserNo +", "+password);
        // 查询出user对象
        UserVo user = loginCheckMapper.getAdmin(UserNo);

        String result = checkLogin(user, UserNo, password);
        if ("right".equals(result)) {
            HttpSession session = request.getSession();
            session.setAttribute("admin", user);
            // 不用默认的转发，使用重定向的方式
            return "redirect:/page/admin/index.html";
        }

        modelMap.addAttribute("msg", result);

        return "forward:/login/admin.html";
    }

    private String checkLogin(UserVo user, String UserNo,
                              String password) {

        // 如果用户名或者密码为空
        if (UserNo == null || password == null) {
            return "用户名密码不能为空！";
        }
        // 如果查询不到此用户
        if (null == user) {
            return "用户名不存在！";
        }
        // 如果查出来的用户没有密码或者姓名
        if (null == user.getPassword() || null == user.getUserName()) {
            return "用户在系统中异常！";
        }
        // String MD5 = MD5Util.md5(password);
        // 如果密码不匹配
        if (!MD5Util.checkPass(password, user.getPassword())) {
            return "密码错误！";
        }

        return "right";
    }

    /**
     * @Description 3.普通用户登出操作
     * @author mzy
     * @time 2018-11-19
     * @see
     * @return   java.lang.String
     * @params  [request]
     */
    @RequestMapping("/api/logout-user")
    public String logOutUser(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute("user");

        return "redirect:/page/user/index.html";
    }

    /**
     * @Description 4.管理员用户登出操作
     * @author mzy
     * @time 2018-11-19
     * @see
     * @return   java.lang.String
     * @params  [request]
     */
    @RequestMapping("/api/logout-admin")
    public String logOutAdmin(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute("admin");

        return "redirect:/page/admin/index.html";
    }

    /**
     * @Description 获取此刻登陆的普通用户的session
     * @author mzy
     * @time 2018-11-19
     * @see
     * @return   java.lang.String
     * @params  []
     */
    @RequestMapping("/api/user/get-session")
    public @ResponseBody
    Object getUserSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");

        return JsonData.buildSuccess(0, user, "操作成功");
    }

    /**
     * @Description 获取此刻登陆的管理员用户的session
     * @author mzy
     * @time 2018-11-19
     * @see
     * @return   java.lang.String
     * @params  []
     */
    @RequestMapping("/api/admin/get-session")
    public @ResponseBody
    Object getAdminSession(HttpSession session) {
        // HttpSession session = request.getSession();
        Object admin = session.getAttribute("admin");

        return JsonData.buildSuccess(0, admin, "操作成功");
    }

    /**
     * @Description 修改普通用户的密码
     * @author mzy
     * @time 2018-11-19
     * @see
     * @return   java.lang.Object
     * @params  [password]
     */
    @PostMapping("/user/change-password")
    public Object changeUserPassword(String password, HttpSession session, ModelMap modelMap) {
        UserVo user = (UserVo) session.getAttribute("user");
        String userNo = user.getUserNo();
        // -----修改密码操作----
        boolean res = changePasswordService.changePassword(password, userNo);
        // --------------------
        session.removeAttribute("user");
        modelMap.addAttribute("msg", "密码已修改，请重新登录！");

        // 思来想去还是forward过去做个msg提示。
        return "forward:/login/user.html";
    }

    /**
     * @Description 修改管理员的密码
     * @author mzy
     * @time 2018-11-19
     * @see
     * @return   java.lang.Object
     * @params  [password]
     */
    @PostMapping("/admin/change-password")
    public Object changeAdminPassword(String password, HttpSession session, ModelMap modelMap) {
        UserVo admin = (UserVo) session.getAttribute("admin");
        String userNo = admin.getUserNo();
        // admin.setPassword(MD5Util.md5(password));
        // -----修改密码操作----
        boolean res = changePasswordService.changePassword(password, userNo);
        // --------------------
        session.removeAttribute("admin");
        modelMap.addAttribute("msg", "密码已修改，请重新登录！");

        return "forward:/login/admin.html";

    }
}

